package main

import (
	"fmt"
)

type DB struct {
	Id int
}

func (db *DB) Query(sql string) {
	fmt.Printf("使用%d连接对象执行SQL语句%s\n", db.Id, sql)
}

type DBPool struct {
	Pool   map[int]*DB
	NextId int
}

func NewDBPool(num int) *DBPool {
	pool := map[int]*DB{}
	for i := 0; i < num; i++ {
		pool[i] = &DB{Id: i}
	}
	return &DBPool{Pool: pool, NextId: num}
}

func (p *DBPool) GetDB() *DB {
	if len(p.Pool) > 0 {
		for id, db := range p.Pool {
			delete(p.Pool, id)
			return db
		}
	}
	db := &DB{Id: p.NextId}
	return db
}

func (p *DBPool) ReleaseDB(db *DB) {
	p.Pool[db.Id] = db
}

func main() {
	pool := NewDBPool(1)
	db1 := pool.GetDB()
	db1.Query("SELECT * FROM USER")
	//pool.ReleaseDB(db1)
	db2 := pool.GetDB()
	db2.Query("SELECT * FROM USER")
}
